package offer;

/**
 * @author zhanb
 * @date 2020/5/20
 */
public class Solution43 {

    public static void main(String[] args) {
        System.out.println(countDigitOne(824883294));
        /*String src = "Little monkey like to eat bananas, eat more into the big monkey, and finally become fat monkey";
        String dest = "monkey";
        int count = 0;
        int index = 0;
        while ((index = src.indexOf(dest)) != -1){
            System.out.println(src);
            src = src.substring(index + dest.length());
            count++;
        }
        System.out.print(count);*/
    }


    /**
     * 面试题43. 1～n整数中1出现的次数
     * 输入一个整数 n ，求1～n这n个整数的十进制表示中1出现的次数。
     *
     * 例如，输入12，1～12这些整数中包含1 的数字有1、10、11和12，1一共出现了5次。
     *
     * 输入：n = 12
     * 输出：5
     *
     * 输入：n = 13
     * 输出：6
     * @param n
     * @return
     */
    public static int countDigitOne(int n) {
        int digit = 1, res = 0;
        int high = n / 10, cur = n % 10, low = 0;
        while(high != 0 || cur != 0) {
            if(cur == 0) {
                res += high * digit;
            } else if(cur == 1) {
                res += high * digit + low + 1;
            } else {
                res += (high + 1) * digit;
            }
            low += cur * digit;
            cur = high % 10;
            high /= 10;
            digit *= 10;
        }
        return res;

    }
}
